package sunwin.yoms.web.controller.person;

import jodd.datetime.JDateTime;
import jodd.util.StringUtil;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import sunwin.yoms.comm.FileHelper;
import sunwin.yoms.comm.YomsException;
import sunwin.yoms.comm.YomsFunction;
import sunwin.yoms.domain.person.UserDomain;
import sunwin.yoms.comm.YomsPage;
import sunwin.yoms.service.comm.YomsDefaultData;
import sunwin.yoms.service.person.UserService;
import sunwin.yoms.service.security.YomsUserDetails;
import sunwin.yoms.web.comm.R;
import sunwin.yoms.web.comm.resolverArg.YomsArrayParam;
import sunwin.yoms.web.comm.resolverArg.YomsDateParam;
import sunwin.yoms.web.comm.YomsAjaxAnswer;
import sunwin.yoms.web.comm.YomsController;
import sunwin.yoms.web.comm.YomsControllerDefaultData;

import java.io.File;
import java.util.Date;
import java.util.List;

/**
 * Created by mt on 2015/7/28.
 */
@Controller
@SuppressWarnings("unchecked")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private YomsControllerDefaultData defaultData;

    private final String FindUvm = "person/user.find";
    private final String CreateUvm = "person/user.create";
    private final String EditUvm = "person/user.edit";
    private final String DeleteUvm = "person/user.delete";
    private final String EditAvm = "person/admin.edit";

    /**
     * 查找用户
     * @param user
     * @param pageIndex
     * @param startTime
     * @param endTime
     * @return
     * @throws YomsException
     */
    @RequestMapping(value = R.FindUser, method = RequestMethod.GET)
    @YomsController(functionNo = YomsFunction.FindUser, viewName = FindUvm)
    public ModelAndView findUser(
            UserDomain user,
            @RequestParam(required = false, defaultValue = "1") int pageIndex,
            @YomsDateParam JDateTime startTime,
            @YomsDateParam JDateTime endTime,
            ModelMap modelMap) throws YomsException {
        modelMap.addAttribute("user", user);
        modelMap.addAttribute("startTime", startTime == null ? null : startTime.toString("YYYY-MM-DD hh:mm"));
        modelMap.addAttribute("endTime", endTime == null ? null : endTime.toString("YYYY-MM-DD hh:mm"));

        YomsPage yomsPage = new YomsPage();
        yomsPage.setPageIndex(pageIndex);
        //判断是否为空，如果为空就设置为空值
        Date date1 = startTime == null ? null : startTime.convertToDate();
        Date date2 = endTime == null ? null : endTime.convertToDate();
        List<UserDomain> users = userService.findUser(user, yomsPage, date1, date2);
        ModelAndView mav = new ModelAndView();
        mav.addObject("yomsPage", yomsPage);
        mav.addObject("users", users);
        return mav;
    }

    /**
     * 访问创建用户页面
     */
    @RequestMapping(value = R.CreateUser, method = RequestMethod.GET)
    @YomsController(viewName = CreateUvm)
    public void createUser() {

    }

    /**
     * 创建用户
     * @param user
     * @return
     * @throws YomsException
     */
    @RequestMapping(value = R.CreateUser, method = RequestMethod.POST)
    @YomsController(functionNo = YomsFunction.CreateUser, viewName = CreateUvm, isAjax = true)
    @ResponseBody
    public YomsAjaxAnswer createUser(UserDomain user) throws YomsException {
        userService.createUser(user);
        YomsAjaxAnswer yomsAjaxAnswer = new YomsAjaxAnswer();
        yomsAjaxAnswer.setSuccess(true);
        return yomsAjaxAnswer;
    }

    /**
     * 访问编辑用户编辑
     * @param id
     * @return
     * @throws YomsException
     */
    @RequestMapping(value = R.EditUser, method = RequestMethod.GET)
    @YomsController(functionNo = YomsFunction.EditUser, viewName = EditUvm)
    public ModelAndView editUser(@RequestParam(required = false, defaultValue = "-1") int id) throws YomsException {
        UserDomain userDomain = userService.getUserById(id);
        ModelAndView mav = new ModelAndView();
        mav.addObject("user", userDomain);
        return mav;
    }

    /**
     * 编辑用户
     * @param userDomain
     * @return
     * @throws YomsException
     */
    @RequestMapping(value = R.EditUser, method = RequestMethod.POST)
    @YomsController(functionNo = YomsFunction.EditUser, viewName = EditUvm, isAjax = true)
    @ResponseBody
    public YomsAjaxAnswer editUser(UserDomain userDomain) throws YomsException {
        userService.updateUser(userDomain);
        YomsAjaxAnswer yomsAjaxAnswer = new YomsAjaxAnswer();
        yomsAjaxAnswer.setSuccess(true);
        return yomsAjaxAnswer;
    }

    /**
     * 访问个人资料页面
     *
     * @return
     * @throws YomsException
     */
    @RequestMapping(value = R.EditAdmin, method = RequestMethod.GET)
    @YomsController(functionNo = YomsFunction.Index, viewName = EditAvm)
    public ModelAndView editAdmin() throws YomsException {
        YomsUserDetails details = defaultData.getCurrentYomsUserDetails();
        UserDomain domain = userService.getAdmin(details);
        details.setRealname(domain.getUserName());
        details.setNickname(domain.getUserNickname());
        details.setAvatar(StringUtil.isBlank(domain.getUserHead()) ? "img/default/default-admin.png" : domain.getUserHead());
        ModelAndView mav = new ModelAndView();
        mav.addObject("admin", details);
        return mav;
    }

    /**
     * 修改个人资料
     *
     * @param details
     * @return
     * @throws YomsException
     */
    @RequestMapping(value = R.EditAdmin, method = RequestMethod.POST)
    @YomsController(functionNo = YomsFunction.Index)
    @ResponseBody
    public YomsAjaxAnswer editAdmin(YomsUserDetails details) throws YomsException {
        YomsUserDetails memoryUser = defaultData.getCurrentYomsUserDetails();
        UserDomain domain = new UserDomain();
        domain.setUserId(memoryUser.getUserid());
        domain.setUserName(details.getRealname());
        domain.setUserNickname(details.getNickname());
        domain.setUserHead("img/avatar/" + details.getAvatar());
        userService.updateUser(domain);
        YomsAjaxAnswer yomsAjaxAnswer = new YomsAjaxAnswer();
        yomsAjaxAnswer.setSuccess(true);
        return yomsAjaxAnswer;
    }

    /**
     * 上传头像
     *
     * @param file img文件
     * @return
     * @throws Exception
     */
    @RequestMapping(value = R.UploadAvator, method = RequestMethod.POST)
    @YomsController(functionNo = YomsFunction.Index)
    @ResponseBody
    public YomsAjaxAnswer upload(@RequestParam(required = false) MultipartFile file) throws YomsException {
        YomsAjaxAnswer answer = YomsAjaxAnswer.getInstance(false);
        if (file != null) {
            YomsUserDetails userDetails = defaultData.getCurrentYomsUserDetails();
            String fileName = userService.saveUserAvatar(file, userDetails);
            answer.setData(fileName);
            answer.setSuccess(true);
        }
        return answer;
    }

    /**
     * 修改密码
     *
     * @param oldpassword
     * @param newpassword
     * @return
     * @throws YomsException
     */
    @RequestMapping(value = R.ChangePassword, method = RequestMethod.POST)
    @YomsController(functionNo = YomsFunction.Index)
    @ResponseBody
    public YomsAjaxAnswer changePassword(String oldpassword, String newpassword) throws YomsException {
        int userid = defaultData.getCurrentYomsUserDetails().getUserid();

        this.userService.changePassword(userid, oldpassword, newpassword);

        return YomsAjaxAnswer.getInstance();
    }


    /**
     * 删除用户
     * @param ids
     * @return
     * @throws YomsException
     */
    @RequestMapping(value = R.DelUser, method = RequestMethod.POST)
    @YomsController(functionNo = YomsFunction.DeleteUser, viewName = DeleteUvm, isAjax = true)
    @ResponseBody
    public YomsAjaxAnswer deleteUser(@YomsArrayParam List<Integer> ids) throws YomsException {
        if (ids != null) {
            for (int id : ids) {
                UserDomain domain = userService.getUserById(id);
                userService.delUser(id);
                delUserAvatar(domain.getUserHead());
            }
        }
        YomsAjaxAnswer yomsAjaxAnswer = new YomsAjaxAnswer();
        yomsAjaxAnswer.setSuccess(true);
        return yomsAjaxAnswer;
    }

    /**
     * 根据角色获取用户
     *
     * @param value
     * @return
     */
    @RequestMapping(value = R.FindUsersByRole, method = RequestMethod.POST)
    @YomsController(functionNo = YomsFunction.FindUser)
    @ResponseBody
    public YomsAjaxAnswer getUserByRole(long value) {
        List<UserDomain> users = userService.getUserByRole(value);

        JSONArray jsonArray = new JSONArray();
        jsonArray.addAll(users);

        YomsAjaxAnswer answer = new YomsAjaxAnswer();
        answer.setSuccess(true);
        answer.setData(jsonArray.toString());

        return answer;
    }

    /**
     * 删除用户相关的图片资源
     */
    private void delUserAvatar(String fileName) {
        if(fileName != null && !fileName.equals("default.admin.png")){
            //获取图片路径
            File file = new File(YomsDefaultData.WebRoot, String.format("img/avatar/%s", fileName));
            //判断图片资源文件夹是否存在
            if (file.exists()) {
                String imgPath = file.getAbsolutePath();
                FileHelper.delFolder(imgPath);
            }
        }
    }
}